package com.rich.dmr.service;


import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.rich.dmr.R;
import com.rich.dmr.handler.DmrHandler;
import com.rich.dmr.ui.fragment.ChannelFragment;
import com.rich.dmr.utils.Constant;
import com.rich.dmr.utils.SoundPoolUtils;
import rich.dmr.DmrManager;
public class DmrService extends Service implements DmrHandler.HandlerCallBack {
    private String TAG = "rich---DmrService";
    private NotificationManager notificationManager;
    private PendingIntent pi;
    private DmrManager dmrManager;
    private static final String CHANNEL_ID = "DMRService";
    private TextToSpeech mSpeech;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d(TAG, "handleMessage===");
            //mSpeech.speak("test", TextToSpeech.QUEUE_FLUSH, null);
            //mSpeech.speak("test", TextToSpeech.QUEUE_FLUSH,null,"dmr_speech");
            mHandler.sendEmptyMessageDelayed(0,200);
        }
    };
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        dmrManager = (DmrManager) getSystemService("dmrservice");

        Intent intents = Intent.makeRestartActivityTask(
                new ComponentName("com.rich.dmr",
                        "com.rich.dmr.ui.activity.MainActivity"));
        pi = PendingIntent.getActivity(this, 0,
                intents, 0, null);
        showNotification();
        //startDmrService();
        SoundPoolUtils.getInstance(this);
        //IntentFilter intentFilter = new IntentFilter();
        //intentFilter.addAction(Constant.ACTION_MODULE_STATE);
        //registerReceiver(broadcastReceiver, intentFilter);
        ServiceMonitor.getInstance().startMonitoring(getApplicationContext());

        //DmrHandler dmrHandler = DmrHandler.getInstance();
        //dmrHandler.setHandlerCallBack(this);
        //TCPServer tcpServer = new TCPServer(10086,this,dmrHandler);
       // boolean isSucceed = tcpServer.start();
        mHandler.obtainMessage(10,0,-1).sendToTarget();
        mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
    }

    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                com.rich.dmr.utils.Log.i(TAG, "onInit: TTS init success");
            }
            else{
                com.rich.dmr.utils.Log.i(TAG, "onInit: TTS init fail");
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand===");

        //mSpeech.speak("test", TextToSpeech.QUEUE_FLUSH,null,"dmr_speech");

        mHandler.sendEmptyMessageDelayed(0,5000);
        return super.onStartCommand(intent, flags, startId);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {

           if (Constant.ACTION_MODULE_STATE.equals(intent.getAction())) {
                int moduleState = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                if (moduleState == 1) {
                    dmrManager.getDigitalVoiceInfo();
                } else if (moduleState == 2) {
                } else if (moduleState == 3) {
                    SoundPoolUtils.getInstance(DmrService.this).playSound(true);
                } else if (moduleState == 4) {
                    SoundPoolUtils.getInstance(DmrService.this).playSound(true);
                }
            }
        }
    };


    public void showNotification() {

        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_running_voice))
                .setContentText(getString(R.string.app_running))
                .setSmallIcon(R.drawable.stat_sys_adb)
                .setWhen(System.currentTimeMillis())
                .setOngoing(true)
                //.setContentIntent(pi)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                .setVibrate(new long[]{0})
                .setSound(null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("dmr-id", "dmr-name",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setBypassDnd(true);
            channel.canBypassDnd();
            channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
            //channel.setDescription("description of this notification");
            channel.setLightColor(Color.GREEN);
            //channel.setName("name of this notification");
            channel.setShowBadge(false);
            channel.enableLights(false);
            channel.enableVibration(false);
            channel.setVibrationPattern(new long[]{0});
            channel.setSound(null, null);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId("dmr-id");
        }

        Notification notification = builder.build();
        //notificationManager.notify(0, notification);
        startForeground(1,notification);
    }

    public void startDmrService(){

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel Channel = new NotificationChannel(CHANNEL_ID,"dmr-service",NotificationManager.IMPORTANCE_HIGH);
        Channel.enableLights(true);
        Channel.setBypassDnd(true);
        Channel.canBypassDnd();
        Channel.setLightColor(Color.RED);
        Channel.setShowBadge(false);
       // Channel.setDescription("ytzn");
        Channel.enableVibration(false);
        Channel.setVibrationPattern(new long[]{0});
        Channel.setSound(null, null);
        Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        manager.createNotificationChannel(Channel);

        Notification notification = new Notification.Builder(this)
                .setChannelId(CHANNEL_ID)
                .setContentTitle(getString(R.string.app_running_voice))
                .setContentText(getString(R.string.app_running))
                .setOngoing(true)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.stat_sys_adb)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                .setVibrate(new long[]{0})
                .setSound(null)
                //.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .build();
        startForeground(1,notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        notificationManager.cancel(0);
        //unregisterReceiver(broadcastReceiver);
        //DmrHandler.getInstance().removeHandlerCallBack(this);
    }

    @Override
    public void updateFrequency(Message msg) {
        switch (msg.what){
            case 5:
                //tcpServer.stop();
                break;
            case 3:
                int color = msg.arg2;
                Log.d(TAG, "color="+color);
                if(color != dmrManager.getColorCode()){
                    dmrManager.setColorCode(color);
                    dmrManager.flush();
                }
                break;
            case 4:
                int group = msg.arg2;
                Log.d(TAG, "group="+group);
                dmrManager.setGroup(group);
                dmrManager.flush();
                break;
        }
    }
}
